<template>
  <div class="chat-sider">
    <div class="logo"></div>
    <div class="menu-list"></div>
    <div class="personal-info"></div>
    <!-- <slot>
      <a-button
        type="primary"
        style="
          font-size: 18px;
          height: 50px;
          border-radius: 6px;
          width: 80%;
          background: linear-gradient(90deg, #56a8ff 1%, #1e8bff 96%);
          margin-bottom: 8px;
        "
        @click="handleCreate"
      >
        +新建会话
      </a-button>

      <div class="dialog-list">
        <div
          v-for="d in chatlist"
          :key="d.id"
          class="dialog-item"
          :class="{ active: activeDialogId === d.id }"
        >
          <div class="main">
            <a-row :align="'middle'">
              <a-col :span="4" @click="() => handleSessionItem(d)">
                <div class="icon icon-dialog" style="font-size: 20px" />
              </a-col>
              <a-col :span="20" class="info name" @click="() => handleSessionItem(d)">
                {{ d.dialogName }}
              </a-col>
            </a-row>
            <a-row @click="() => handleSessionItem(d)">
              <a-col :offset="4" :span="10">
                <div class="date">
                  {{ getDate(d.lastQuetionTime) }}
                </div>
              </a-col>
            </a-row>
          </div>
          <div class="more">
            <a-dropdown trigger="click" overlay-class-name="f-dropdown">
              <MoreIcon />
              <template #overlay>
                <a-menu @click="handleMenuClick($event, d)">
                  <a-menu-item key="remove" >删除</a-menu-item>
                  <a-menu-item key="rename" >
                    重命名
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
        </div>
      </div>

      <a-modal v-model:visible="showCreateDialogModal" :title="modalTitle" @ok="handleUpdate">
        <a-form>
          <a-form-item label="会话名称" :required="true">
            <a-input v-model:value="dialogName" :maxlength="20" />
          </a-form-item>
        </a-form>
      </a-modal>
    </slot> -->
     
    <!-- <template v-if="showMenu">
      <a-space direction="vertical" class="menu-list" :gap="8">
        <RouterLink to="/chat/documentParsing" class="menu-item">
          <div class="icon icon-all-dialog" />
          文档解读
        </RouterLink>
        <RouterLink to="/chat/list" class="menu-item">
          <div class="icon icon-all-dialog" />
          所有会话
        </RouterLink>

        <a v-show="hasManage" class="menu-item" href="/manage/user" target="__blank"
          ><div class="icon icon-admin" />
          后台管理
        </a>

        <div class="menu-item">
          <a-dropdown trigger="click">
            <span
              ><user-outlined class="icon" style="font-size: 22px; color: #707c97" />{{
                userInfo.name
              }}</span
            >
            <template #overlay>
              <a-menu @click="handleLogout">
                <a-menu-item key="remove"> 退出登录 </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </a-space>
    </template> -->
  </div>
</template>
<script lang="ts" setup>
import { UserOutlined } from '@ant-design/icons-vue'
import { page, saveOrUpdate, remove } from '@/api/dialog'
import type { IDialogData } from '@/api/type'
import { getDate } from '@/utils'
import { Modal, message } from 'ant-design-vue'
import { computed, onBeforeMount,  ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserInfoStore } from '@/stores/modules/userInfo'
import { getDetail } from '@/api/user'
import { useChatBus } from '@/hook/useChatBus'
import { isUndefined } from 'lodash'
import { useMenuStore } from '@/stores/modules/menu'
import MoreIcon from '@/components/MoreIcon.vue'
defineOptions({
  name: 'ChatSider'
})

const { showMenu } = defineProps({
  showMenu: {
    type: Boolean,
    default: true
  }
})
const menuStore = useMenuStore()

const userInfo = useUserInfoStore()
const dialogName = ref('')
const showCreateDialogModal = ref(false)
const dialogId = ref('')
const modalTitle = computed(() => (dialogId.value === '' ? '新建会话' : '重命名会话'))
const chatlist = ref<IDialogData[]>([])
const route = useRoute()
const activeDialogId = computed(() => {
  return route.params?.id
})

const router = useRouter()
function handleSessionItem(item: IDialogData) {
  router.push(`/chat/${item.id}`)
}

function getTopDialogList() {
  console.log('userInfo', userInfo.id)
  return page({
    userId: userInfo.id as string,
    pageSize: '10'
  }).then((res) => {
    if (!res.data.ok) return res
    chatlist.value = res.data.entity.rows
    return res
  })
}

const hasManage = ref(false)
function getDialogPage() {
  console.log('getDialogPage')
  return getTopDialogList().then((res) => {
    if (!res.data.ok) return
    if (!chatlist.value?.[0]) return
    const first = chatlist.value?.[0]
    //避免详情页重复跳转
    if (first && route.name === 'chatDefault') {
      console.log('route', route)
      handleSessionItem(first)
    }
  })
}

function getUserDetail() {
  if(!userInfo.id)return
  getDetail(userInfo.id as string).then((res) => {
    if (!res.data.ok) return
    const has = res.data.entity.isManager || res.data.entity.isSuperManager
    console.log('has', res.data)
    hasManage.value = has === 1
    if (isUndefined(res.data.entity.searchType)) return
    console.log('http://192.168.30.34:81/zentao/bug-view-31386.html')
    bus.emit('setEnhence', res.data.entity.searchType)
  })
}

onBeforeMount(() => {
  getDialogPage()
  getUserDetail()
})

const bus = useChatBus((e) => {
  switch (e) {
    case 'refreshDiaglogName':
      getDialogPage()
      break
    default:
      break
  }
})

watch(route, () => {
  getUserDetail()
})

function handleMenuClick(e: { key: string }, item: IDialogData) {
  const { key } = e

  const id = item.id
  const name = item.dialogName
  switch (key) {
    case 'remove': {
      Modal.confirm({
        title: '确定删除',
        content: `该会话吗`,
        onOk() {
          remove(id).then(() => {
            bus.emit('refreshDiaglogName')
            const currentDialogId = route.params.id
            if (currentDialogId !== id) return
            if (!chatlist.value?.[0]) return
            const first = chatlist.value?.[0]
            handleSessionItem(first)
          })
        }
      })
      break
    }
    case 'rename': {
      dialogId.value = id
      dialogName.value = name
      showCreateDialogModal.value = true
      break
    }
  }
}

function handleCreate() {
  saveOrUpdate({
    id: dialogId.value,
    userId: userInfo.id as string,
    dialogName: dialogName.value
  }).then((res) => {
    if (!res.data.ok) return
    createdCallback()
    showCreateDialogModal.value = false
    dialogId.value = ''
    dialogName.value = ''
  })
}

function handleUpdate() {
  if (!dialogName.value.length) {
    message.error('会话名称不能为空')
    return
  }
  saveOrUpdate({
    id: dialogId.value,
    userId: userInfo.id as string,
    dialogName: dialogName.value
  }).then((res) => {
    if (!res.data.ok) return

    showCreateDialogModal.value = false
    dialogId.value = ''
    dialogName.value = ''
    bus.emit('refreshDiaglogName')
  })
}

function createdCallback() {
  console.log('createdCallback')
  /**
   * 获取第一个、跳转
   */
  getTopDialogList().then((res) => {
    if (!res.data.ok) return
    const first = chatlist.value?.[0]
    if (!first) return
    handleSessionItem(first)
  })
}

function handleLogout() {
  userInfo.loginOut().then(() => {
    router.push('/')
  })
}
</script>

<style lang="scss" scoped>
.chat-sider {
  display: flex;
  align-items: center;
  flex-flow: column;
  max-width: 250px;
  padding: 0 0;
  height: 100vh;
  border-right: 1px solid #E7E9EC;
}

.icon {
  margin-right: 16px;
  width: 20px;
  height: 20px;
}
.logo {
  flex: none;
  height: 60px;
  width: 100%;
  background-image: url('@/assets/sider-new.png');
  background-size: 168px 36px;
  background-repeat: no-repeat;
  background-position: 24px 12px;
  display: flex;
  align-items: center;
  flex-flow: column;
  margin-bottom: 30px;
  border-bottom: 1px solid #e7e9ec;
}

.dialog-list {
  padding: 16px 0;
  width: 100%;
  flex: auto;
  overflow-y: auto;
}
.dialog-item {
  width: 100%;
  padding: 8px 20px 8px 24px;
  margin: 4px 0;
  user-select: none;
  border: 3px solid transparent;
  color: #0d1c2e;
  display: flex;
  align-items: center;
  .main {
    flex: auto;
  }
  .more {
    opacity: 0;
    cursor: pointer;
  }
  &:hover,
  &.active {
    .more {
      opacity: 1;
    }
  }
  .info {

    text-align: left;
    font-size: 16px;
    line-height: 26px;
    color: #0d1c2e;
  }

  .name {
    width: 120px;
    overflow: hidden;
    white-space: nowrap;
    word-break: break-all;
    text-overflow: ellipsis;
  }
  .date {
    min-width: 100px;
    color: #707c97;
  }

  &:hover {
    background-color: #f7f9fc;
  }

  &.active {
    background-color: #f3f5f8;
    border-left-color: #2a8bf2;

    .icon-dialog {
      background-image: url('@/assets/dialog-active.png');
    }
  }
}
.menu-list {
  width: 100%;
  margin-bottom: 24px;
  padding-top: 8px;
  border-top: 1px solid #e7e9ec;

  .menu-item {
    display: flex;
    align-items: center;
    width: 100%;
    text-align: left;
    padding: 12px 24px;
    font-size: 16px;
    cursor: pointer;
    color: #0d1c2e;
    .icon {
      width: 24px;
      height: 24px;
    }

    .icon {
      margin-right: 16px;
    }
  }
}
</style>
